/**
 * 数据打点上报工具js
 */
import aesHelper from '@/utils/aesHelper'
import $$Rangers from '@datarangers/sdk-mp'
import common from '@/config/env/common'
import netconfig from '@/config/netconfig'
import { login } from '@/utils/mpHelper'
import { getOpenId as getOpenIdApi } from '@/api/account'
import { TrackType, trackEvent } from './tracks'
import { useApplianceStore } from '../../src/store/appliance'
import { reject } from 'lodash'

const isReport = common.isReportRangersData
const reportLogSwitch = common.reportRangeDataLogSwitch

/**
 * 初始化火山埋点sdk
 */
export function initRangersSDK() {
  if (!isReport) {
    return
  }
  var openid = ''
  var unionID = ''

  try {
    let key = uni.getStorageSync('cache_key')
    let iv = uni.getStorageSync('cache_iv')
    openid = aesHelper.decrypt(uni.getStorageSync('openid'), key, iv)
    unionID = aesHelper.decrypt(uni.getStorageSync('unionid'), key, iv)
  } catch (error) {}
  initRangers(openid, unionID) //初始化火山埋点sdk
}

/**
 * 事件上报
 * @param {事件名} eventName
 * @param {数据对象} propObj
 */
export function reportEventData(eventName: any, propObj: any) {
  if (!isReport) {
    return
  }
  let page = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null
  let rangersData = JSON.parse(JSON.stringify(propObj))

  reportRangersData(eventName, rangersData, page)
}

async function getOpenid(callback: { (openid: any, unionid: any): void; (arg0: string, arg1: string): void }) {
  let openid = ''
  let unionid = ''
  try {
    const d = await login()
    if (!d.code) {
      openid = ''
      callback(openid, unionid)
      return
    }

    const res = await getOpenIdApi(d.code)

    openid = res.data.openid
    unionid = res.data.unionid

    callback(openid, unionid)
  } catch (e) {
    openid = ''
    callback(openid, unionid)
  }
}

/**
 * 初始化火山SDK
 */
function initRangers(openid: string, unionid: string) {
  $$Rangers.init({
    app_id: netconfig.datarangersAppId, // 参考2.1节获取，注意类型是number而非字符串
    channel_domain: netconfig.datarangersDataServerUrl, // 设置私有化部署数据上送地址
    log: reportLogSwitch, // 是否开启日志打印
    auto_report: true, // 上报所有预定义事件
    enable_storage: true, //是否开启离线缓存
    enable_buffer: true, // 设置true后，将开启缓冲
    buffer_interval: 6000, // 缓冲的间隔时间，单位是毫秒，默认值 5000，含义是到达间隔时间后会上报缓冲区的所有事件
    buffer_number: 6, // 缓冲的最大数量，默认值 5，含义是缓冲数量达到该值后会立即上报缓冲区的所有事件
    enable_cache: true, // 开启后，请求失败的事件会存到storage中，并在用户下一次再进小程序时补充上报
    enable_ab_test: true, // 打开A/BTest
  })
  $$Rangers.config({
    mp_name: 'HomeConnect',
    bsh_mp_version: netconfig.VERSION,
    enable_ab_test: true, // 打开A/BTest
  })

  if (openid && unionid) {
    $$Rangers.config({
      user_unique_id: unionid,
      openid: openid,
    })
    $$Rangers.send() // 此时调用send方法，所有事件在此时才会上报
  } else {
    getOpenid((openid, unionid) => {
      if (openid && unionid) {
        $$Rangers.config({
          user_unique_id: unionid,
          openid: openid,
        })
        $$Rangers.send() // 此时调用send方法，所有事件在此时才会上报
      }
    })
  }
}
/**
 * 火山埋点上报
 *
 * @param {*} eventName
 * @param {*} propObj
 */
function reportRangersData(eventName: string, propObj: { [x: string]: any }, page: { route: any }) {
  let pages = getCurrentPages() //获取加载的页面
  if (pages && pages.length > 0) {
    let currentPage = pages[pages.length - 1] //获取当前页面的对象
    try {
      let lastPage = pages[pages.length - 2] //获取上个页面的对象
      propObj.last_path = lastPage.route
    } catch (error) {}
    if (currentPage) {
      propObj.$current_path = currentPage.route
    } else if (page && page.route) {
      propObj.$current_path = page.route
    }
    // 增加current_path判空
    if (propObj.$current_path) {
      let appids = ['wx850d691fd02de8a1', 'wx7d9e9cbea92ce71f', 'wx577c74fb940daaea']
      let result = appids.filter((element) => {
        return propObj.$current_path.indexOf(element) != -1
      })
      if (result && result.length > 0) {
        let startLen = propObj.$current_path.indexOf(result[0]) + result[0].length + 1
        propObj.$current_path = propObj.$current_path.slice(startLen)
      }
    }
  }
  var phoneNumber = ''
  try {
    let key = uni.getStorageSync('cache_key')
    let iv = uni.getStorageSync('cache_iv')
    phoneNumber = aesHelper.decrypt(uni.getStorageSync('ciamId'), key, iv)
  } catch (error) {}
  if (phoneNumber) {
    propObj.account_Number = phoneNumber.replace('+86', '')
  }
  // 埋点日志
  if (reportLogSwitch) {
    console.log('埋点key', eventName, '埋点属性', propObj)
  }
  $$Rangers.event(eventName, propObj)
}

export function safeTrack<TTrackFunc extends Function = () => any, TContext = any>(fn: TTrackFunc, ctx?: TContext) {
  try {
    fn.call(ctx)
  } catch (e) {
    console.error('埋点数据处理报错: ', e)
  }
}

export async function applianceControlTrack<TTrackFunc extends Function = () => any>(
  fn: TTrackFunc,
  trackKey?: string,
  trackData?: any,
  buttonId?: string
) {
  let res: any = null
  try {
    res = await fn()
  } catch (error) {
    res = error
  } finally {
    if (res === undefined) {
      res = {}
    }
    safeTrack(() => {
      trackData['successOrNot'] = 'code' in res ? res.code == 0 : false
      trackData['error_code'] = 'code' in res ? res.code : -1
      trackData['response_msg'] = 'msg' in res ? res.msg : 'unknow'
      trackEvent(trackKey ? trackKey : 'trackKey', trackData, TrackType.ApplianceDetail, buttonId)
    })
    return res
  }
}

export function dataRangeConfigGlobalApplianceInfo() {
  // 获取本地存储的家电信息
  let applianceHaId = useApplianceStore().current?.haId || ''
  let applianceVib = useApplianceStore().current?.vib || ''
  let applianceType = useApplianceStore().current?.type || ''
  let applianceBrand = useApplianceStore().current?.brand || ''
  try {
    $$Rangers.config({
      global_appliance_haid: applianceHaId,
      global_appliance_vib: applianceVib,
      global_appliance_type: applianceType,
      global_appliance_brand: applianceBrand,
    })
  } catch (error) {
    console.error('配对全局家电属性出错:', error)
  }
}
